<template>
  <div class="authManage-container">
    <a-row>
      <!-- 树搜索 -->
      <a-col :span="7">
        <!--        <a-card>-->
        <div style="display: flex; align-items: center;height: 50px">
          <div>默认权限：</div>
          <div style="height: 28px;line-height: 28px;background: #f2f2f2;padding: 0 10px;margin-right: 10px">
            查看横向本级扩展一层的数据
          </div>
          <a-radio-group
            name="checked"
            v-model:value="checked"
            :disabled="isLook"
          >
            <a-radio
              :value="1"
              @click.native="radioChange"
              v-if="checked == 1"
            ></a-radio>
            <a-radio
              :value="0"
              @click.native="radioChange"
              v-else
            ></a-radio>
          </a-radio-group>
        </div>
        <!-- 公司组织树搜索 -->
        <tree-organization
                class="o-z"
          ref="treeOrganization"
          :expand-by-auto="true"
          :selected-keys.sync="selectedKeys"
          :select-options.sync="selectOptions"
          :contain-virtual="true"
          :show-child-with-search="true"
          :expanded-keys="expandedKeys"
          :auto-select="false"
          @onSelect="handleSelect"
          @searchEmpty="handleSearchEmpty"
          @initFinish="initFinish"
        />
        <!--        </a-card>-->
      </a-col>
      <a-col
        :span="17"
        style="padding-left: 20px"
        class="s-c"
      >
        <!--        <a-card>-->
        <div
          class="search"
          style="margin-bottom: 10px;overflow: hidden"
        >
          <a-row :gutter="[10]">
            <a-col :span="10">
              <div style="display: flex;align-items: center; height: 32px">
                <div style="width: 100px;text-align: right">
                  组织名称：
                </div>
                <a-input
                  v-model="nameLike"
                  allowClear
                  placeholder="请输入组织名称"
                />
              </div>
            </a-col>
            <a-col :span="8">
              <div style="display: flex;align-items: center; height: 32px">
                <span>只显示项目：</span>
                <a-switch
                  v-model:checked="swichChecked"
                  checked-children="开"
                  un-checked-children="关"
                />
              </div>
            </a-col>
            <a-col :span="6">
              <a-button
                type="primary"
                style="margin-right: 10px"
                @click="search"
              >
                搜索
              </a-button>
              <a-button @click="reset">重置</a-button>
            </a-col>
          </a-row>
        </div>
        <div
          class="scorll-area"
          style="margin-bottom: 10px"
        >
          <div
            class="cell"
            v-for="(item, index) in unitList"
            :key="item.id"
          >
            {{item.pName || item.name}}
            <div
              class="del"
              @click="delRow(item,index)"
              v-if="!isLook"
            >
              x
            </div>
          </div>
        </div>
        <list-table
          ref="table"
          :columns="columns"
          :request="loadData"
          :alert="true"
          row-key="id"
          :show-page="false"
          :row-selection="rowSelection"
          :isInit="false"
        >
          <template
            slot="sort"
            slot-scope="text, record, index"
          >
            <span>{{ index + 1 }}</span>
          </template>
          <template
            slot="postPNames"
            slot-scope="text, record, index"
          >
            <div
              class="ellipsis"
              :title="filterPostPName(text)"
            >
              {{ filterPostPName(text) }}
            </div>
          </template>
        </list-table>
        <!--        </a-card>-->
      </a-col>
    </a-row>
  </div>
</template>
<script>
import { getOrgManageList } from '@/api/system/system'
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    width: '65px',
    scopedSlots: { customRender: 'sort' }
  },
  {
    title: '组织名称',
    dataIndex: 'name'
  },
  {
    title: '组织层级',
    dataIndex: 'pName'
  }
]
const searchArr = [
  {
    name: '用户名称',
    value: 'nameLike',
    type: 'input'
  },
  {
    name: '工号',
    value: 'jobNumLike',
    type: 'input'
  },
  {
    name: '电话',
    value: 'phoneLike',
    type: 'input'
  },
  {
    name: '岗位',
    value: 'postNameLike',
    type: 'input'
  }
]
export default {
  name: 'AuthManage',
  components: {
    TreeOrganization
  },
  props: {
    selectOrgList: {
      type: Array,
      default: () => []
    },
    defaultNum: {
      type: Number,
      default: 1
    },
    orgin: {
      type: String,
      default: ''
    }
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      expandedKeys: [],
      nameLike: '',
      checked: 1, // 横向查看
      swichChecked: false,
      childInitData: {},
      visible: {
        update: false,
        auth: false
      },
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      queryParam: {},
      statisticsInfo: {
        totalNum: 0
      },
      selectedRowKeys: [],
      selectedRows: [],
      unitList: [],
      tableData: [],
      rootId: '',
      isLook: false,
      cacheTableData: [],
      cacheSelectedRowKeys: []
    }
  },
  computed: {
    rowSelection() {
      if (this.isLook) {
        return null
      }
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  watch: {
    selectOrgList: {
      handler(newVal) {
        this.unitList = newVal
        const ids = []
        this.unitList.forEach((item) => {
          ids.push(item.id)
        })
        this.cacheSelectedRowKeys = ids
        this.selectedRowKeys = ids
      },
      immediate: true
    },
    defaultNum: {
      handler(newVal) {
        this.checked = newVal
      },
      immediate: true
    }
  },
  mounted() {
    if (this.$route.query.pageType == 'look' || this.orgin) {
      this.isLook = true
    }
    // 组织树获取数据
    this.$refs.treeOrganization.getList()
  },
  methods: {
    initFinish(data) {
      this.rootId = data.data[0].id
      this.expandedKeys = [data.data[0].id]
      this.$refs.table.getData()
    },
    setChecked(val) {
      this.checked = val
    },
    radioChange() {
      if (this.checked == 1) {
        this.checked = 2
      } else {
        this.checked = 1
      }
      this.$emit('setDefalt', this.checked == 1 ? 1 : 0)
    },
    delRow(row, index) {
      const idx1 = this.cacheSelectedRowKeys.findIndex((item) => item === row.id)
      if (idx1 >= 0) {
        this.cacheSelectedRowKeys.splice(idx1, 1)
      }
      const idx = this.selectedRowKeys.findIndex((item) => item === row.id)
      if (idx >= 0) {
        this.selectedRowKeys.splice(idx, 1)
      }
      this.unitList.splice(index, 1)
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      const cancelId = []
      this.tableData.forEach((item) => {
        if (!selectedRowKeys.includes(item.id)) {
          cancelId.push(item.id)
        }
      })
      this.cacheSelectedRowKeys.push(...selectedRowKeys)
      const arr = []
      //去重
      this.cacheSelectedRowKeys.forEach((item) => {
        if (!arr.includes(item)) {
          arr.push(item)
        }
      })
      const newId = []
      arr.forEach((item) => {
        if (!cancelId.includes(item)) {
          newId.push(item)
        }
      })

      this.cacheSelectedRowKeys = newId

      //找岗位
      const newPost = []
      this.unitList.forEach((item) => {
        if (this.cacheSelectedRowKeys.includes(item.id)) newPost.push(item)
      })
      //
      const newTPost = []
      this.tableData.forEach((item) => {
        if (this.cacheSelectedRowKeys.includes(item.id)) {
          newTPost.push(item)
        }
      })

      this.unitList = [...newPost, ...newTPost]
      //去重
      const arrLast = []
      this.unitList.forEach((item) => {
        if (!this.findId(arrLast, item.id)) {
          arrLast.push(item)
        }
      })
      console.log(arrLast, 'arrLast')
      this.unitList = arrLast
      this.$emit('setUnitList', this.unitList)
    },
    handleSearchEmpty() {
      this.selectedKeys = []
      this.selectOptions = {}
    },
    handleSelect(e) {
      this.handleSearch({
        pathLike: e.id || void 0
      })
    },
    filterPostPName(val) {
      if (val === null) return ''
      return (
        val.reduce &&
        val.reduce((pre, cur) => {
          return pre === '' ? cur : pre + '、' + cur
        }, '')
      )
    },
    findId(arr, id) {
      let flag = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
          flag = true
          break
        }
      }
      return flag
    },
    async loadData(parameter) {
      const requestParameters = Object.assign({}, parameter, {
        pageNum: 1,
        pageSize: 99999,
        containVirtual: false,
        resultWithLeaderName: true,
        pathLike: this.rootId,
        ...this.queryParam,
        types: '1,3'
      })
      return getOrgManageList(requestParameters).then(async (res) => {
        // const resp = await this.loadFirstLeve()
        let obj = {
          code: '0',
          data: [...res.data.list]
        }
        let arr = obj.data.filter((item) => item.name !== '分包商' && item.name != '分公司')
        this.tableData = arr
        obj.data = arr
        const data = []
        this.tableData.forEach((item) => {
          if (this.cacheSelectedRowKeys.includes(item.id)) {
            data.push(item.id)
          }
        })
        this.selectedRowKeys = data
        return obj
      })
    },
    async loadFirstLeve() {
      const data = {
        pageNum: 1,
        pageSize: 99999,
        containVirtual: false,
        resultWithLeaderName: true,
        id: this.queryParam.pathLike || this.rootId,
        type: this.queryParam.type,
        ...this.queryParam
      }
      const res = await getOrgManageList(data)
      return res
    },
    handleUpdate(type, data = {}) {
      if (type === 'auth') {
        this.childInitData = { ...data, id: data.userId }
        this.visible.auth = true
        return
      }
      this.$router.push({
        path: '/systemManage/menuPermissions/authManage/UpdateAuthManage',
        query: {
          pageType: type,
          id: data.id || '',
          userId: data.userId || ''
        }
      })
    },
    reset() {
      this.nameLike = ''
      this.swichChecked = false
      this.queryParam = {
        pathLike: this.queryParam.pathLike
      }
      this.$refs.table.refresh(true)
    },
    search() {
      this.queryParam.nameLike = this.nameLike
      this.queryParam.type = this.swichChecked ? 3 : null
      this.$refs.table.refresh(true)
    },
    handleSearch(val) {
      this.queryParam = {
        ...this.queryParam,
        ...val
      }
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
.cell {
  padding-left: 10px;
  padding-right: 20px;
  position: relative;
  background: #108eea;
  color: #fff;
  min-width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin-right: 15px;
  margin-bottom: 10px;
}
.scorll-area {
  max-height: 100px;
  min-height: 50px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
}
.del {
  position: absolute;
  right: 10px;
  top: 0;
  cursor: pointer;
}
/deep/ .anticon-setting.tableIcon {
  display: none;
}
</style>
